<template>
  <div class="dashboard-container">

    <div class="filter-container">
      <el-row :gutter="10" style="width:100%">
        <el-col :span="4">
          <el-input
            v-model="listQuery.package_no"
            placeholder="集包号"
            class="input-with-select"
            @keypress.enter.native="reloadList"
          />
        </el-col>
        <el-col :span="4">
          <el-input
            v-model="listQuery.username"
            placeholder="创建人"
            class="input-with-select"
            @keypress.enter.native="reloadList"
          />
        </el-col>

        <el-col :span="4">
          <el-date-picker
            v-model="listQuery.created"
            style="width: 100%;"
            type="datetimerange"
            range-separator="~"
            value-format="yyyy-MM-dd HH:mm:ss"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']"
          />
        </el-col>
        <el-col :span="10">
          <div style="display:flex">
            <el-button
              class="filter-item"
              type="primary"
              icon="el-icon-search"
              @click="reloadList"
            >搜索</el-button>
            <el-button
              class="filter-item"
              style="margin-left: 10px;"
              icon="el-icon-edit"
              type="primary"

              @click="addNews"
            >
              添加
            </el-button>
            <el-button
              class="filter-item"
              style="margin-left: 10px;"
              icon="el-icon-printer"
              type="primary"
              @click="printAll"
            >
              批量打印
            </el-button>
            <download-excel
              style="margin-left:10px"
              class="export-excel-wrapper"
              :fetch="importPackageList"
              :fields="json_fields"
              type="xls"
              worksheet="My Worksheet"
              name="集包详情导出"
              :before-generate="startDownload"
              :before-finish="finishDownload"
            >
              <el-button type="primary">导出EXCEL</el-button>
            </download-excel>
            <el-select v-model="printerName" placeholder="请选择打印机" style="width: 420px;margin-left:10px">
              <el-option
                v-for="item in printerList"
                :key="item.name"
                :label="item.name"
                :value="item.name"
              />
            </el-select>

          </div>

        </el-col>
      </el-row>
    </div>
    <div style="padding:0 20px">

      <el-table
        ref="multipleTable"
        v-loading="listLoading"
        :data="list"
        height="calc(100vh - 200px)"
        style="width: 100%;"
        size="mini"
        border
        tooltip-effect="dark"
        :header-cell-style="{ background: '#eaf1fd', color: '#333' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column
          label="集包号"
          prop="package_no"
        />
        <el-table-column
          label="集包类型"
        >
          <template slot-scope="{ row }">
            <div>
              <span v-if="row.size == 1">小件</span>
              <span v-if="row.size == 2">大件</span>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="备注"
          min-width="300px"
          prop="desc"
        /> -->
        <el-table-column
          label="订单数量"
          width="150px"
          prop="count"
        />
        <el-table-column
          label="操作人"
          width="150px"
          prop="admin.username"
        />
        <el-table-column
          label="创建时间"
          prop="created"
          width="140px"
        />
        <el-table-column
          label="操作"
          align="right"
          width="250"
          class-name="small-padding fixed-width"
          fixed="right"
        >
          <template slot-scope="{ row }">
            <el-button
              size="mini"
              type="primary"
              @click="edit(row)"
            >
              查看详情
            </el-button>
            <el-button
              type="danger"
              @click="delet(row)"
            >
              废弃
            </el-button>
            <el-button
              type="primary"
              @click="print(row)"
            >
              打印
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />
    </div>
    <Detial :detial="detial" :status="status" :visible="visible" @update="closeDraw" @reload="reloadList" />
    <el-dialog
      title="集包新增"
      :visible.sync="dialogVisible"
      width="400px"
      :before-close="handleClose"
    >
      <!-- <div style="padding:20px"><el-input
        v-model="desc"
        type="textarea"
        placeholder="请输入备注"
        class="input-with-select"
      /></div> -->
      <div class="dialog-item">
        <span>数量:</span>
        <el-input-number v-model="num" style="width:200px" :min="1" label="数量" />
      </div>
      <div class="dialog-item">
        <span>集包类型:</span>
        <el-select v-model="size" style="width:200px" placeholder="请选择">
          <el-option
            label="小件"
            :value="1"
          />
          <el-option
            label="大件"
            :value="2"
          />
        </el-select>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addPackage">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listPackage, delPackage, createPackage, packageLabel, importPackage } from '@/api/ware/index'

import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import Detial from './components/packageDetial.vue'
import { doConnect, doPrint } from '@/utils/print'
import _ from 'lodash'

// import XLSXS from '@/lib/xlsx-style/index'
export default {
  name: 'Dashboard',
  components: {
    Pagination,
    Detial
  },
  data() {
    return {
      num: 1,
      size: '',
      printerName: '',
      data_arr: [],
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        package_no: '',
        username: '',
        created: []
      },
      visible: false,
      status: 1,
      id: '',
      detial: {},
      dialogVisible: false,
      desc: '',
      printerList: [],
      printLoading: null,
      back: {},
      selectList: [],

      json_fields: {
        集包号: 'package_no',
        系统订单号: {
          field: 'tid',
          callback: value => {
            return '&nbsp;' + value
          }
        },
        主运单号: {
          field: 'first_waybill_no',
          callback: value => {
            return '&nbsp;' + value
          }
        },
        状态: {
          field: 'status',
          // 自定义回调函数
          callback: value => {
            if (value === 102) return '待取号'
            if (value === 103) return '已取号'
            if (value === 104) return '已发货'
            if (value === 201) return '已废弃'
          }
        },
        用户昵称: 'user.username',
        客户昵称: 'client.username',
        客户唛头: 'receiver.user_mark',
        来源单号: 'order_no',
        收件人: 'receiver.name',
        电话: 'mobile',
        地址: 'address',
        走件渠道: 'channel.name',
        货物类型: 'goods_type.name',
        大小件: {
          field: 'size',
          // 自定义回调函数
          callback: value => {
            if (value === 0) return '未选择'
            if (value === 1) return '小件'
            if (value === 2) return '大件'
          }
        },
        // 订单类型: {
        //   field: 'order_type',
        //   callback: value => {
        //     if (value === 0) return '未选择'
        //     if (value === 1) return '仓储'
        //     if (value === 2) return '非仓储'
        //   }
        // },
        // 送货方式: {
        //   field: 'delivery_method',
        //   callback: value => {
        //     if (value === 0) return '未选择'
        //     if (value === 1) return '上门取件'
        //     if (value === 2) return '自送货物'
        //   }
        // },
        快递产品类型: {
          field: 'express_type',
          // 自定义回调函数
          callback: value => {
            if (value === 0) return '未选择'
            if (value === 1) return '标快'
            if (value === 2) return '特快'
          }
        },
        批次号: 'batch_no',
        '揽件重量(kg)': 'weight_pickup',
        '发运重量(kg)': 'weight_send',
        '结算重量(kg)': 'weight',
        账单金额: 'pay_cost',
        下单时间: 'created'
      },
      json_data: []
    }
  },
  computed: {

  },
  watch: {
    back(val) {
      this.printLoading.close()
    }
  },
  mounted() {
    var that = this
    const socket = doConnect()
    socket.onmessage = function(event) {
      console.log(JSON.parse(event.data))
      const res = JSON.parse(event.data)
      if (res.cmd === 'getPrinters') {
        that.printerList = res.printers
      }
      if (res.cmd === 'print') {
        that.printLoading = that.$loading({
          lock: true,
          text: '打印中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
      }
      if (res.cmd === 'notifyPrintResult') {
        that.back = res
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleSelectionChange(val) {
      this.selectList = val
    },
    print(row) {
      packageLabel({
        package_nos: [row.package_no]
      }).then(res => {
        doPrint(res.data.list, res.data.templateURL, this.printerName)
      })
    },
    printAll() {
      if (!this.selectList.length) {
        this.$message.error('请选择集包')
        return
      }
      const arr = this.selectList.map(item => {
        return item.package_no
      })
      packageLabel({
        package_nos: arr
      }).then(res => {
        doPrint(res.data.list, res.data.templateURL, this.printerName)
      })
    },
    closeDraw() {
      this.visible = false
    },
    handleClose() {
      this.dialogVisible = false
    },
    addNews() {
      this.dialogVisible = true
      this.size = ''
      this.num = 1
      this.desc = ''
    },
    edit(row) {
      this.detial = { ...row }
      this.status = 2
      this.visible = true
    },
    delet(row) {
      this.$confirm('确认废弃该集包, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delPackage({
          id: row.id
        }).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getList()
        })
      }).catch(() => {

      })
    },
    reloadList() {
      this.listQuery.page = 1
      this.visible = false
      this.getList()
    },
    getList() {
      this.listLoading = true
      listPackage(this.listQuery).then(response => {
        this.list = response.data.data
        this.total = response.data.total
        this.listLoading = false
      })
    },
    addPackage() {
      createPackage({
        num: this.num,
        size: this.size
      }).then(res => {
        this.$message({
          type: 'success',
          message: '添加成功!'
        })
        this.dialogVisible = false
        this.getList()
      })
    },
    downLoad() {

    },
    getPageSize() {
      return new Promise((resolve, reject) => {
        importPackage(this.listQuery).then(response => {
          resolve(response.data.total)
        })
      })
    },
    getExcelList(page) {
      return new Promise((resolve, reject) => {
        importPackage({
          page: page,
          limit: this.listQuery.limit,
          package_no: this.listQuery.package_no,
          username: this.listQuery.username,
          created: this.listQuery.created
        }).then(response => {
          response.data.data.forEach(item => {
            item.mobile = '+' + _.get(item.receiver, 'area_code', '') + ' ' + _.get(item.receiver, 'mobile', '')
            item.address = _.get(item.receiver, 'nation', '') + _.get(item.receiver, 'province', '') + _.get(item.receiver, 'city', '') + _.get(item.receiver, 'district', '') + _.get(item.receiver, 'detailed', '')
          })

          resolve(response.data.data)
        })
      })
    },
    async importPackageList() {
      const total = await this.getPageSize()
      const page = Math.ceil(total / this.listQuery.limit)
      var data = []
      for (let i = 1; i <= page; ++i) {
        data = data.concat(await this.getExcelList(i))
      }
      return data
    },
    startDownload() {
      this.loadingExcel = this.$loading({
        lock: true,
        text: '导出表格中，请稍后...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    finishDownload() {
      this.loadingExcel.close()
    }
  }
}
</script>
<style scoped lang="scss">
.filter-container{
  padding:20px 20px 10px;
}

.upload-demo{
  margin: 20px 0 10px;
}
.dialog-item{
  display: flex;
  padding: 0 20px;
  margin-top: 20px;
  align-items: center;
  span{
   width: 80px;
    text-align: right;
    margin-right: 10px;
  }
}
</style>
